package com.cade.agriculturemall.view.personalCenter.ordersManage;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.DeleteCallback;
import com.bumptech.glide.Glide;
import com.cade.agriculturemall.R;
import com.cade.agriculturemall.base.BaseAdapter;
import com.cade.agriculturemall.base.BaseViewHolder;
import com.cade.agriculturemall.model.OrderEntity;
import com.cade.agriculturemall.model.ShoppingCarsEntity;
import com.cade.agriculturemall.utils.ConverUtil;
import com.cade.agriculturemall.view.personalCenter.ordersManage.OrderItems.OrderActivity;
import com.cade.agriculturemall.view.shoppingCar.settlement.SettlementAdapter;
import com.cade.agriculturemall.view.shoppingCar.settlement.SettlementViewModel;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hshunxin on 2018/1/30.
 */

public class MerchandiseListAdapter extends BaseAdapter implements View.OnClickListener {
    //    private List<OrderEntity> dataList = new ArrayList<>();
    public Context mContext;
    private List<SettlementViewModel> models = new ArrayList<>();
    private MyClickListener myClickListener;

    public MerchandiseListAdapter(Activity baseActivity, MyClickListener myClickListener) {
        super();
        mContext = baseActivity;
        this.myClickListener = myClickListener;
    }

    public void setModels(List<SettlementViewModel> models) {
        this.models = models;
    }


    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        BaseViewHolder baseViewHolder = null;
        switch (viewType) {
            case SettlementViewModel.TYPE_ORDER_TIME:
                baseViewHolder = new BaseViewHolder(parent, R.layout.item_settlement_order_time);
                break;
            case SettlementViewModel.TYPE_SJ:
                baseViewHolder = new BaseViewHolder(parent, R.layout.item_settlement_shoper);
                break;
            case SettlementViewModel.TYPE_CP:
                baseViewHolder = new BaseViewHolder(parent, R.layout.item_settlement_good);
                break;
            case SettlementViewModel.TYPE_OPERATE_BUTTON:
                baseViewHolder = new BaseViewHolder(parent, R.layout.item_order_footer);
                break;
        }
        return baseViewHolder;
    }

    @Override
    public int getItemViewType(int position) {
        return models.get(position).getType();
    }

    OrderEntity orderEntity = new OrderEntity();

    @Override
    public void onBindViewHolderWrapper(BaseViewHolder holder, final int position) {
        int viewType = getItemViewType(position);
        switch (viewType) {
            case SettlementViewModel.TYPE_ORDER_TIME:
                orderEntity = (OrderEntity) models.get(position).getObject();
                TextView tvTime = holder.findViewById(R.id.item_settlement_order_time_tv);
                TextView tvState = holder.findViewById(R.id.item_settlement_order_time_info_tv);
                tvTime.setText("下单时间" + orderEntity.getOrderSetttlementTime());
                if (TextUtils.isEmpty(orderEntity.getOrderStatus())) {
                    tvState.setText("kong");
                } else {
                    showState(orderEntity.getOrderStatus(), tvState);
                }
                break;
            case SettlementViewModel.TYPE_SJ:
                String shopName = (String) models.get(position).getObject();
                TextView tvShoper = holder.findViewById(R.id.item_setttlement_address);
                tvShoper.setText(shopName);
                break;
            case SettlementViewModel.TYPE_CP:
                ShoppingCarsEntity entity = (ShoppingCarsEntity) models.get(position).getObject();
                TextView tvMerchandiseName = holder.findViewById(R.id.item_setttlement_good_tv_name);
                TextView tvMerchandiseCount = holder.findViewById(R.id.item_setttlement_good_tv_count);
                TextView tvMerchandisePrice = holder.findViewById(R.id.item_setttlement_good_tv_price);
                ImageView imageView=holder.findViewById(R.id.item_setttlement_good_img);
                if(entity.getProId().getPicture().size()!=0) {
                    Glide.with(mContext).load(entity.getProId().getPicture().get(1)).into(imageView);
                }
                tvMerchandisePrice.setText("￥" + Float.parseFloat(entity.getPrice() + ""));
                tvMerchandiseName.setText(entity.getProId().getTitle());
                tvMerchandiseCount.setText("×" + entity.getQuantitate());
                break;
            case SettlementViewModel.TYPE_OPERATE_BUTTON:
                tvPay = holder.findViewById(R.id.item_order_price_tv_pay_certain);
                tvDelete = holder.findViewById(R.id.item_order_price_btn_delete);
                tvLogistics = holder.findViewById(R.id.item_order_price_btn_logistics);
                tvReturn = holder.findViewById(R.id.item_order_price_btn_return);
                tvCancel = holder.findViewById(R.id.item_order_price_btn_cancel);
                tvToPay = holder.findViewById(R.id.item_order_price_btn_pay);
                tvToPay.setTag(position - 1);
                tvPost = holder.findViewById(R.id.item_order_price_tv_info_post);
                tvReceive = holder.findViewById(R.id.item_order_price_tv_receive);
                tvPay.setText("￥" + orderEntity.getOrderPrice());
                tvDelete.setOnClickListener(this);
                tvLogistics.setOnClickListener(this);
                tvReturn.setOnClickListener(this);
                tvCancel.setOnClickListener(this);
                tvToPay.setOnClickListener(this);
                tvPost.setOnClickListener(this);
                tvDelete.setTag(position);
                tvLogistics.setTag(position);
                tvReturn.setTag(position);
                tvCancel.setTag(position);
                tvToPay.setTag(position);
                tvPost.setTag(position);
                setFootView(orderEntity.getOrderStatus());
                break;
        }
    }

    TextView tvDelete, tvLogistics, tvReturn, tvCancel, tvToPay, tvPost, tvPay, tvReceive;

    public void setFootView(String orderStatus) {
        String status = ConverUtil.transOrderStatus(orderStatus, 2);
        switch (status) {
            case "1":
//                        未发货：催促发货 退货
                tvReturn.setVisibility(View.VISIBLE);
                tvPost.setVisibility(View.VISIBLE);
                break;
            case "2":
//                        未收货：查看物流 退货
                tvReturn.setVisibility(View.VISIBLE);
                tvLogistics.setVisibility(View.VISIBLE);
                tvReceive.setVisibility(View.VISIBLE);
                break;
            case "3":
                /*
                * 评价未实现*/
//                        已完成未评价：删除 查看物流 退货 评价
                tvDelete.setVisibility(View.VISIBLE);
                tvLogistics.setVisibility(View.VISIBLE);
                tvReturn.setVisibility(View.VISIBLE);
                break;
            case "4":
//                        已完成评价：删除 查看物流 追加评价
                tvDelete.setVisibility(View.VISIBLE);
                tvLogistics.setVisibility(View.VISIBLE);
                break;
            case "5":
//                        未支付：取消订单 付款
                tvCancel.setVisibility(View.VISIBLE);
                tvToPay.setVisibility(View.VISIBLE);
                break;
            case "6":
//                        取消：删除
                tvDelete.setVisibility(View.VISIBLE);
                break;

        }
    }

    @Override
    public int getItemCount() {
        return models.size();
    }

    int tag;

    @Override
    public void onClick(View view) {
        tag = (int) view.getTag();
        switch (view.getId()) {
            case R.id.item_order_price_btn_delete:
//                Toast.makeText(mContext, "已完成 已评价,删除订单", Toast.LENGTH_SHORT).show();
                showDialog();
                break;
            case R.id.item_order_price_btn_logistics:
                Toast.makeText(mContext, "跳转物流页面", Toast.LENGTH_SHORT).show();
                break;
            case R.id.item_order_price_btn_return:
                Toast.makeText(mContext, "跳转退货页面", Toast.LENGTH_SHORT).show();
                break;
            case R.id.item_order_price_btn_cancel:
                showDialog();
                break;
            case R.id.item_order_price_btn_pay:
//                Toast.makeText(mContext, "未支付,去支付页面", Toast.LENGTH_SHORT).show();
                OrderEntity entity = (OrderEntity) models.get((Integer) tvToPay.getTag()).getObject();
                myClickListener.goPayClick(entity.getOrderId());
                break;
            case R.id.item_order_price_tv_info_post:
                Toast.makeText(mContext, "已提醒卖家发货", Toast.LENGTH_LONG).show();
                break;
        }

    }

    public List<SettlementViewModel> getModels() {
        return models;
    }

    /**
     * 根据订单状态修改样式
     *
     * @param stateOrder
     * @param textView
     */
    private void showState(String stateOrder, TextView textView) {
        String stateInfo = ConverUtil.transOrderStatus(stateOrder, 1);
        String text = "empty";
        if ("3".equals(stateInfo)) {
            text = "交易成功";
        } else if (stateInfo.equals("2")) {
            text = "待收货";
        } else if ("1".equals(stateInfo)) {
            text = "待发货";
        } else if ("4".equals(stateInfo)) {
            text = "待评价";
        } else if ("5".equals(stateInfo)) {
            text = "待支付";
        } else if (stateInfo.equals("6")) {
            text = "已关闭";
        }
        textView.setText(text);
        textView.setVisibility(View.VISIBLE);
    }

    public void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setMessage("删除后订单不可恢复，是否继续删除订单？")
                .setTitle("确认删除订单？")
                .setPositiveButton("取消", null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        goodsDelete(orderEntity);
                    }
                });
        builder.show();
    }

    public void goodsDelete(final OrderEntity orderEntity) {
        String objectId = orderEntity.getObjectId();
        AVQuery<AVObject> deleteOrder = new AVQuery<>("order");
        deleteOrder.whereEqualTo("objectId", objectId);
        deleteOrder.deleteAllInBackground(new DeleteCallback() {
            @Override
            public void done(AVException e) {
                if (e != null) {
                    deleteFail();
                } else {
                    deleteSuccess();
                    refreshView();
                }
            }
        });
    }


    public void deleteSuccess() {
        Toast.makeText(mContext, "订单删除成功", Toast.LENGTH_SHORT);

    }

    public void refreshView() {
        for (int i = 0; i < tag; i++) {
            models.remove(tag - i);
            if (models.get(tag - i).getType() == SettlementViewModel.TYPE_ORDER_TIME) {
                break;
            }
        }
        notifyDataSetChanged();
    }

    public void deleteFail() {
        Toast.makeText(mContext, "订单不可删除", Toast.LENGTH_SHORT);
    }

    public interface MyClickListener {
        void goPayClick(String orderObjectId);
    }
}
